/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.smarttmt.smartmanager.controller;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.smarttmt.smartmanager.entity.Solucion;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;
import org.smarttmt.smartmanager.controller.exceptions.NonexistentEntityException;
import org.smarttmt.smartmanager.controller.exceptions.PreexistingEntityException;
import org.smarttmt.smartmanager.controller.exceptions.RollbackFailureException;
import org.smarttmt.smartmanager.entity.Causrequ;

/**
 *
 * @author nicolas
 */
public class CausrequJpaController implements Serializable {

    public CausrequJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Causrequ causrequ) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (causrequ.getSolucionList() == null) {
            causrequ.setSolucionList(new ArrayList<Solucion>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            List<Solucion> attachedSolucionList = new ArrayList<Solucion>();
            for (Solucion solucionListSolucionToAttach : causrequ.getSolucionList()) {
                solucionListSolucionToAttach = em.getReference(solucionListSolucionToAttach.getClass(), solucionListSolucionToAttach.getSolucodi());
                attachedSolucionList.add(solucionListSolucionToAttach);
            }
            causrequ.setSolucionList(attachedSolucionList);
            em.persist(causrequ);
            for (Solucion solucionListSolucion : causrequ.getSolucionList()) {
                Causrequ oldSolucadeOfSolucionListSolucion = solucionListSolucion.getSolucade();
                solucionListSolucion.setSolucade(causrequ);
                solucionListSolucion = em.merge(solucionListSolucion);
                if (oldSolucadeOfSolucionListSolucion != null) {
                    oldSolucadeOfSolucionListSolucion.getSolucionList().remove(solucionListSolucion);
                    oldSolucadeOfSolucionListSolucion = em.merge(oldSolucadeOfSolucionListSolucion);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findCausrequ(causrequ.getCarecodi()) != null) {
                throw new PreexistingEntityException("Causrequ " + causrequ + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Causrequ causrequ) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Causrequ persistentCausrequ = em.find(Causrequ.class, causrequ.getCarecodi());
            List<Solucion> solucionListOld = persistentCausrequ.getSolucionList();
            List<Solucion> solucionListNew = causrequ.getSolucionList();
            List<Solucion> attachedSolucionListNew = new ArrayList<Solucion>();
            for (Solucion solucionListNewSolucionToAttach : solucionListNew) {
                solucionListNewSolucionToAttach = em.getReference(solucionListNewSolucionToAttach.getClass(), solucionListNewSolucionToAttach.getSolucodi());
                attachedSolucionListNew.add(solucionListNewSolucionToAttach);
            }
            solucionListNew = attachedSolucionListNew;
            causrequ.setSolucionList(solucionListNew);
            causrequ = em.merge(causrequ);
            for (Solucion solucionListOldSolucion : solucionListOld) {
                if (!solucionListNew.contains(solucionListOldSolucion)) {
                    solucionListOldSolucion.setSolucade(null);
                    solucionListOldSolucion = em.merge(solucionListOldSolucion);
                }
            }
            for (Solucion solucionListNewSolucion : solucionListNew) {
                if (!solucionListOld.contains(solucionListNewSolucion)) {
                    Causrequ oldSolucadeOfSolucionListNewSolucion = solucionListNewSolucion.getSolucade();
                    solucionListNewSolucion.setSolucade(causrequ);
                    solucionListNewSolucion = em.merge(solucionListNewSolucion);
                    if (oldSolucadeOfSolucionListNewSolucion != null && !oldSolucadeOfSolucionListNewSolucion.equals(causrequ)) {
                        oldSolucadeOfSolucionListNewSolucion.getSolucionList().remove(solucionListNewSolucion);
                        oldSolucadeOfSolucionListNewSolucion = em.merge(oldSolucadeOfSolucionListNewSolucion);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = causrequ.getCarecodi();
                if (findCausrequ(id) == null) {
                    throw new NonexistentEntityException("The causrequ with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Causrequ causrequ;
            try {
                causrequ = em.getReference(Causrequ.class, id);
                causrequ.getCarecodi();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The causrequ with id " + id + " no longer exists.", enfe);
            }
            List<Solucion> solucionList = causrequ.getSolucionList();
            for (Solucion solucionListSolucion : solucionList) {
                solucionListSolucion.setSolucade(null);
                solucionListSolucion = em.merge(solucionListSolucion);
            }
            em.remove(causrequ);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Causrequ> findCausrequEntities() {
        return findCausrequEntities(true, -1, -1);
    }

    public List<Causrequ> findCausrequEntities(int maxResults, int firstResult) {
        return findCausrequEntities(false, maxResults, firstResult);
    }

    private List<Causrequ> findCausrequEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Causrequ.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Causrequ findCausrequ(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Causrequ.class, id);
        } finally {
            em.close();
        }
    }

    public int getCausrequCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Causrequ> rt = cq.from(Causrequ.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
